﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LotteryVote.Entity;
using System.Web;
using System.Web.Security;
using LotteryVote.Data;
using LotteryVote.Utility;

namespace LotteryVote.Logic
{
    public class LoginFacade
    {
        private UserDataAccess daUser;
        private LoginLogDataAccess _daLoginLog;
        internal LoginLogDataAccess DaLoginLog
        {
            get
            {
                if (_daLoginLog == null)
                    _daLoginLog = new LoginLogDataAccess();
                return _daLoginLog;
            }
            set
            {
                _daLoginLog = value;
            }
        }
        public LoginFacade()
        {
            daUser = new UserDataAccess();
        }

        public bool Login(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");
            var user = daUser.GetUserByUserName(userName);
            if (user == null || !(EncryptHelper.Equal(password, user.UserInfo.Password))) return false;
            FormsAuthentication.SetAuthCookie(userName, false);
            SetCurrentUser(user);
            DaLoginLog.AddLog(user);
            return true;
        }
        public void Logout()
        {
            FormsAuthentication.SignOut();
            SetCurrentUser(null);
        }
        public bool IsLogin
        {
            get
            {
                return GetCurrentUser() != null;
            }
        }

        public User GetCurrentUser()
        {
            var user = HttpContext.Current.Items["CurrentUser"] as User;
            if (user != null) return user;

            object userObj = HttpContext.Current.Session["CurrentUser"];
            if (userObj == null) return null;
            int userId;
            try
            {
                userId = Convert.ToInt32(userObj);
            }
            catch (Exception ex)
            {
                LogConsole.Error("获取UserId失败!", ex);
                return null;
            }
            user = daUser.GetUserById(userId);
            SetCurrentUser(user);
            return user;
        }

        private void SetCurrentUser(User user)
        {
            HttpContext.Current.Items["CurrentUser"] = user;

            object userId = null;
            if (user != null) userId = user.UserId;

            HttpContext.Current.Session["CurrentUser"] = userId;
        }
    }
}
